﻿namespace Leetcode.N0016;
public class Solution
{
    public int ThreeSumClosest(int[] nums, int target)
    {
        nums = nums.OrderBy(i => i).ToArray();
        int ans = 0;
        int min = int.MaxValue;
        for (int n1 = 0; n1 < nums.Length; n1++)
        {
            if (n1 > 0 && nums[n1] == nums[n1 - 1])
            {
                continue;
            }
            int n2 = n1 + 1;
            int n3 = nums.Length - 1;

            while (n2 < n3)
            {
                var val = nums[n1] + nums[n2] + nums[n3];

                if (val > target)
                {
                    int val2;
                    while (n3 - n2 > 1 && (val2 = nums[n1] + nums[n2] + nums[n3 - 1]) > target)
                    {
                        val = val2;
                        n3--;
                    }

                    n3--;
                }
                else
                {

                    int val2;
                    while (n3 - n2 > 1 && (val2 = nums[n1] + nums[n2 + 1] + nums[n3]) < target)
                    {
                        val = val2;
                        n2++;
                    }
                    n2++;
                }

                if (val == target)
                {
                    return val;
                }
                var absVal = Math.Abs(val - target);
                if (min > absVal)
                {
                    ans = val;
                    min = absVal;
                }
            }
        }
        return ans;
    }
}